package com.sc.everyonerentboot.controller;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.github.pagehelper.PageInfo;
import com.sc.everyonerentboot.pojo.Result;
import com.sc.everyonerentboot.pojo.Users;
import com.sc.everyonerentboot.service.UserService;
import com.sc.everyonerentboot.util.JwtUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.Resource;
import org.springframework.core.io.UrlResource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.net.MalformedURLException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

@RestController
@RequestMapping("/user")
public class UserController {
    @Autowired
    UserService us;
    @RequestMapping("/register")
    public Result register(@RequestParam("u") String userJson,@RequestParam("avatarFile")MultipartFile file){
        if (file.isEmpty()){
            return new Result(0,"请选择头像");
        }
        String filePath=us.avatar(file);
        if (filePath==null){
            return new Result(0,"头像上传失败");
        }
        Users u = null;
        try {
            ObjectMapper objectMapper = new ObjectMapper();
            u = objectMapper.readValue(userJson, Users.class);
        } catch (JsonProcessingException e) {
            throw new RuntimeException(e);
        }
        u.setAvatar(filePath);
        int num=us.register(u);
        if (num>0){
            return new Result(1,"注册成功");
        }
        return new Result(0,"注册失败");
    }
    @RequestMapping("/login")
    public Result login(@RequestBody Users u){
        Users user=us.login(u);
        if (user!=null){
            user.setToken(JwtUtils.createToken(u));
            return new Result(1,"登录成功",user);
        }
        return new Result(0,"账号或密码错误");
    }
    @RequestMapping("/update")
    public Result update(@RequestBody Users u){
        int num=us.update(u);
        if (num>0){
            return new Result(1,"修改成功");
        }
        return new Result(0,"修改失败");
    }
    @RequestMapping("/delAll")
    public Result delAll(@RequestBody Integer[] ids){
        int num= us.delAll(ids);
        if (num>0){
            return new Result(1,"删除成功"+num+"条数据");
        }
        return new Result(0,"删除失败");
    }
    @RequestMapping("/del")
    public Result del(Integer id){
        int num= us.del(id);
        if (num>0){
            return new Result(1,"删除成功"+num+"条数据");
        }
        return new Result(0,"删除失败");
    }
    @RequestMapping("/showAll")
    public Result showAll(@RequestParam(defaultValue = "1") Integer pageNum,
                             @RequestParam(defaultValue = "10") Integer pageSize,
                             @RequestBody Users u){
        PageInfo<Users> pages=us.showAll(pageNum,pageSize,u);
        if (pages.getList().size()!=0){
            return new Result(1,"查询成功",pages);
        }
        return new Result(0,"无数据",pages);
    }


//    头像上传
    @RequestMapping("/avatarUp")
    public Result avtarUp(@RequestParam("avatar")MultipartFile file){
        if (file.isEmpty()){
            return new Result(0,"请选择头像");
        }
        String filePath=us.avatar(file);
        return new Result(0,filePath);
    }


    //读取头像
    @GetMapping("/avatars/{filename:.+}")
    @ResponseBody
    public ResponseEntity<Resource> serveFile(@PathVariable String filename) throws MalformedURLException {
        Path file;
        Resource resource;
        if(filename==null || filename.trim().isEmpty() || filename.equals("undefined")){
            file = Paths.get("EveryoneRentBoot/target/classes/avatars/default.jpg");
        }
        else {
            file = Paths.get("EveryoneRentBoot/target/classes/avatars").resolve(filename);
        }
        String contentType = "application/octet-stream"; // 默认二进制流
        resource = new UrlResource(file.toUri());
        // 根据文件扩展名设置正确的 MIME 类型
        try {
            contentType = Files.probeContentType(file);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return ResponseEntity.ok()
                .header(HttpHeaders.CONTENT_DISPOSITION, "inline; filename=\"" + resource.getFilename() + "\"")
                .contentType(MediaType.parseMediaType(contentType))
                .body(resource);
    }
}
